import { useMemo, useRef, useState } from 'react';
import { PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, message, Upload } from 'antd';
import { useRequest } from 'ahooks';
import { productRemove } from '@/services/productApi';
import { useModel } from '@umijs/max';

// 示例数据
// const data = [
// { id: 1, college: '张三', class: 28, arrangeCourse: '北京市海淀区' },
// { id: 2, college: '李四', class: 30, arrangeCourse: '上海市浦东新区' },
// { id: 3, colldege: '王五', class: 25, arrangeCourse: '广州市天河区' },
// { id: 4, college: '赵六', class: 35, arrangeCourse: '深圳市南山区' },
// ];

var data = JSON.parse(localStorage.getItem('filteredCourseData') || '[]');

// data = data.shift();

// 将更新后的数组重新存储到 localStorage 中
// localStorage.setItem('filteredCourseData', JSON.stringify(data));

interface InitialStateType {
    name: string;
    webSocket: WebSocket | null;
}

export default function SupervisionCoursePage() {
    const { initialState } = useModel('@@initialState');

    if (!initialState || !initialState.webSocket) {
        console.error('WebSocket is not available in the initial state');
        return null;
    }

    const requestRemove = useRequest(productRemove, {
        manual: true, // 关闭自动请求
        onSuccess: () => {
            // 重新加载表格
            //   tableActionRef.current?.reload();
        },
    });

    // 上传新的课表
    const [fileList, setFileList] = useState<any[]>([]);
    const [isModalVisible, setIsModalVisible] = useState(false);

    const handleFileChange = (info: any) => {
        const { file } = info;
        if (file.status === 'done') {
            setIsModalVisible(true);
            if (initialState.webSocket) {
                const reader = new FileReader();
                reader.onload = async (e) => {
                    const arrayBuffer = e.target?.result;
                    if (arrayBuffer instanceof ArrayBuffer) {
                        // 将 ArrayBuffer 转换为 Base64 字符串
                        const base64Data = arrayBufferToBase64(arrayBuffer);

                        initialState.webSocket.send(JSON.stringify({ data: base64Data, fileName: file.name, type: "UpdateCourseInfo" }));
                        setIsModalVisible(false);
                        message.success('文件上传中...');
                    } else {
                        message.error('文件读取失败');
                    }
                };
                reader.readAsArrayBuffer(file.originFileObj);
            }
        } else if (file.status === 'error') {
            message.error(`${file.name} - 文件上传失败`);
        }
    };

    // 测试 ws 链接

    const columns = useMemo<ProColumns[]>(
        () => [
            {
                title: '上课院系',
                dataIndex: '上课院系',
                key: 'college',
                hideInSearch: true,
            },
            {
                title: '上课班级',
                dataIndex: '上课班级',
                key: 'class',
            },
            {
                title: '排课人数',
                dataIndex: '排课人数',
                key: 'arrangeCourse',
                hideInSearch: true,
            },
            {
                title: '选课人数',
                dataIndex: '选课人数',
                key: 'selectCourse',
                hideInSearch: true,
            },
            {
                title: "开课单位",
                dataIndex: '开课单位',
                key: 'unit',
                hideInSearch: true,

            },
            {
                title: "开课课程",
                dataIndex: '开课课程',
                key: 'course',

            },
            {
                title: "授课教师",
                dataIndex: '授课教师',
                key: 'teacher',

            },
            {
                title: "开课时间",
                dataIndex: '开课时间',
                key: 'time',
                renderText: (val) => `第${String(val).split(' ')[1]}`,
                filters: [
                    { text: '第1-2节', value: '第12节' },
                    { text: '第3-4节', value: '第34节' },
                    { text: '第1-4节', value: '第1234节' },
                    { text: '第5-6节', value: '第56节' },
                    { text: '第7-8节', value: '第78节' },
                    { text: '第5-8节', value: '第5678节' },
                    { text: '第9-10节', value: '第910节' },
                ],
                onFilter: (value, record) => `第${String(record.开课时间).split(' ')[1]}` === value,

            },
            {
                title: "上课地点",
                dataIndex: '上课地点',
                key: 'address',

            },
            {
                title: "上课周次",
                dataIndex: '上课周次',
                key: 'selectWeek',
                hideInSearch: true,
            },
            {
                title: "星期",
                dataIndex: '星期',
                key: 'week',
                // 添加筛选功能
                sorter: (a, b) => a.星期 - b.星期,
                filters: [
                    { text: '周一', value: '1' },
                    { text: '周二', value: '2' },
                    { text: '周三', value: '3' },
                    { text: '周四', value: '4' },
                    { text: '周五', value: '5' },
                    { text: '周六', value: '6' },
                    { text: '周日', value: '7' },
                ],
                onFilter: (value, record) => record.星期 === value,
            },
        ],
        [requestRemove.loading],
    );

    return (
        <PageContainer title="课程管理">
            <ProTable
                columns={columns}
                dataSource={data}
                rowKey="id"
                options={{ fullScreen: true, density: true, setting: true }}
                // pagination={{
                //     pclassSize: 5,
                // }}
                toolBarRender={() => [
                    <Upload
                        key="upload"
                        onChange={handleFileChange}
                        showUploadList={false}
                        disabled={isModalVisible}
                    >
                        <Button type="primary">选择新课表</Button>
                    </Upload>,
                ]}
            />
        </PageContainer>
    );

}


function arrayBufferToBase64(buffer: ArrayBuffer): string {
    let binary = '';
    const bytes = new Uint8Array(buffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
}

